package com.mywork.mvpkodeinxml.app

import android.app.Application
import android.util.Log
import com.mywork.mvpkodeinxml.BuildConfig
import com.mywork.mvpkodeinxml.di.appKodeinModule
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.LogStrategy
import com.orhanobut.logger.Logger
import com.orhanobut.logger.PrettyFormatStrategy
import com.zchu.rxcache.RxCache
import com.zchu.rxcache.diskconverter.GsonDiskConverter
import me.jessyan.autosize.AutoSizeConfig
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.generic.bind
import org.kodein.di.generic.instance
import java.io.File

class App : Application(), KodeinAware {
    override val kodein: Kodein = Kodein.lazy {
        bind() from instance(filesDir)//Logger
        import(appKodeinModule)
    }

    companion object {
        lateinit var instance: App
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        //logger
        val formatStrategy = PrettyFormatStrategy.newBuilder()
            .showThreadInfo(false)
            .tag("XML-Log")
            .logStrategy(LogCatStrategy())
            .build()

        Logger.addLogAdapter(object : AndroidLogAdapter(formatStrategy) {
            override fun isLoggable(priority: Int, tag: String?): Boolean {
                return BuildConfig.DEBUG
            }
        })

        //AndroidAutoSize
        AutoSizeConfig.getInstance()
            .setExcludeFontScale(true)//是否屏蔽系统字体大小对 AndroidAutoSize 的影响, 如果为 true, App 内的字体的大小将不会跟随系统设置中字体大小的改变
            .setLog(BuildConfig.DEBUG)////是否打印 AutoSize 的内部日志

        //RxCache
        RxCache.initializeDefault(
            RxCache.Builder()
                .appVersion(1)
                .diskDir(File(cacheDir.path + File.separator + "data-cache"))
                .diskConverter(GsonDiskConverter())
                .diskMax((1024 * 1024 * 1024).toLong())
                .memoryMax(1 * 1024 * 1024)
                .setDebug(BuildConfig.DEBUG)
                .build()
        )
    }

    //由于AS3.0打印相同TAG时，会自动隐藏前面TAG，造成排版问题，把TAG增加乱数可解决排版问题
    inner class LogCatStrategy : LogStrategy {

        private var last: Int = 0

        override fun log(priority: Int, tag: String?, message: String) {
            Log.println(priority, randomKey() + tag!!, message)
        }

        private fun randomKey(): String {
            var random = (10 * Math.random()).toInt()
            if (random == last) {
                random = (random + 1) % 10
            }
            last = random
            return random.toString()
        }
    }
}